package com.xh.car.util;

import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author PangJunjie
 * @Date 2024/4/24/024
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getSession().getAttribute("loginInfo") == null) {
            /*请求类型判断*/
            String xRequestWith = request.getHeader("X-Requested-With");
            if (xRequestWith != null && xRequestWith.contains("XMLHttpRequest")) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println(JSON.toJSON(R.error(401, "请先登录！")));
            } else {
                response.sendRedirect(request.getContextPath() + "/");
            }
            return false;
        }
        return true;
    }
}
